package com.example.mqtt.demo.controller;

import com.example.mqtt.demo.Constants;
import com.example.mqtt.demo.pub.IPubService;
import com.example.mqtt.demo.sub.ISubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * <B>概要说明：</B> <BR>
 *
 * @author zhoulin1@xsyxsc.com
 * @since 2021-07-21 16:40
 */
@Slf4j
@RestController
public class DemoRestController {

	@Autowired(required = false)
	IPubService pubService;

	@Autowired(required = false)
	ISubService subService;

	@PostConstruct
	public void init() {
		// 订阅主题
		if (null != subService) {
			subService.subscribeMessage(Constants.TOPIC_LOOP_TEST);
		}
	}

	@RequestMapping(value = "/mqtt/loop/message", method = RequestMethod.POST)
	public String index(@RequestBody String data) {
		pubService.publishMessage(Constants.TOPIC_LOOP_TEST, data);
		this.enable = true;
		return "Success";
	}

	private boolean enable = true;
	@Scheduled(initialDelay = 2000, fixedDelay = 2000)
	public void send() throws InterruptedException {
		if (enable) {
			pubService.publishMessage(Constants.TOPIC_LOOP_TEST, new Date().toString());
			Thread.sleep(1000);
		}
	}

}
